package com.markerhub.controller;


import com.baomidou.mybatisplus.extension.api.R;
import com.markerhub.common.lang.Result;
import com.markerhub.dto.VisitsRecordDto;
import com.markerhub.entity.Notice;
import com.markerhub.service.NoticeService;
import com.markerhub.utils.RedisUtil;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author MarkerHub
 * @since 2022-04-20
 */
@RestController

@RequestMapping("/notice")
public class NoticeController extends BaseController {
    @Autowired
    NoticeService noticeService;

    @Autowired
    RedisUtil redisUtil;
    @PostMapping(value = "/upload", produces = "application/json;charset=UTF-8")
    @PreAuthorize("hasAuthority('sys:notice')")
    public Result notice(Notice notice, HttpServletRequest request) {
        if(notice.getTitle().equals("")){
            return Result.fail("标题不能为空！");
        }

        MultipartFile file = null;
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if(notice.getContent().equals("")&&isMultipart){
            return Result.fail("内容或文件不能为空！");
        }
        if (isMultipart){
            MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
            file = multipartRequest.getFile("file");

        }
        return  noticeService.noticePublish(notice, file);
    }

    @GetMapping("/list")
    public Result getNoticeList(){

        return Result.succ(noticeService.getNoticeList());
}
    @PostMapping(value = "/update", produces = "application/json;charset=UTF-8")
    public Result update(Notice notice, HttpServletRequest request) {
        MultipartFile file = null;
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart){
            MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
            file = multipartRequest.getFile("file");

        }
        return  noticeService.updateNotice(notice, file);
    }
    @PostMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('sys:delete')")
    public Result delete(@PathVariable("id") Long id) {
        noticeService.removeById(id);
        return Result.succ("删除成功");
    }
}
